﻿using UnityEngine;
using System.Collections;

public class UIToast : MonoBehaviour {

    public UILabel text;
    public UISprite background;
    private Vector3 mSize = Vector3.zero;

    private static UIToast instance;

    public static UIToast Instance
    { get { return instance; } }

    void Awake()
    {
        instance = this;
        DontDestroyOnLoad(this);
        text.gameObject.SetActive(true);
        background.gameObject.SetActive(true);
        this.gameObject.SetActive(false);
    }
    public void SetText (string tooltipText)
	{

        //MusicManager.Instance.PlaySource("tip");
        if (text != null && !string.IsNullOrEmpty(tooltipText))
        {
            text.text = tooltipText;

            Transform textTrans = text.transform;
            Vector3 offset = textTrans.localPosition;
            Vector3 textScale = textTrans.localScale;

            // 计算文本的大小
            mSize = text.printedSize;

            mSize.x *= textScale.x;
            mSize.y *= textScale.y;

            //计算背景图片的大小
            if (background != null)
            {
                Vector4 border = background.border;
                mSize.x += border.x + border.z + (offset.x - border.x) * 0.1f;
                mSize.y += border.y + border.w + (-offset.y - border.y) * 0.1f;

                background.width = Mathf.RoundToInt(mSize.x);
                background.height = Mathf.RoundToInt(mSize.y)+30;
            }
        }
        this.gameObject.SetActive(true);
        StartCoroutine(HideToast());
    }

    IEnumerator HideToast()
    {
        yield return new WaitForSeconds(3);
        this.gameObject.SetActive(false);
    }
}
